package com.yupi.springbootinit.aop;

import com.yupi.springbootinit.annotation.AuthCheckXzh;
import com.yupi.springbootinit.common.BaseResponseXzh;
import com.yupi.springbootinit.common.ErrorCodeXzh;
import com.yupi.springbootinit.controller.UserCollentXzh;
import com.yupi.springbootinit.exception.BusinessExceptionXzh;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.enums.UserRoleEnum;
import com.yupi.springbootinit.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 用户权限校验
 * xiezhihao
 */
@Aspect
@Component
public class AuthIntercepotXzh {
    @Resource
    private UserCollentXzh userCollentXzh;
    /**
     * 执行拦截
     */
    @Around("@annotation(authCheckXzh)")
    public Object doIntercepot(ProceedingJoinPoint joinPoint, AuthCheckXzh authCheckXzh) throws Throwable {
        String mustRole = authCheckXzh.mustRole();
        // 通过请求上下文 获得属性
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 获得当前登录用户
        BaseResponseXzh<User> getlogin = userCollentXzh.getlogin(request);
        User user = getlogin.getData();
        UserRoleEnum mustRoleEmun = UserRoleEnum.getEnumByValue(mustRole);
        if (Objects.isNull(mustRoleEmun)){
            // 不需要权限 放行
            return joinPoint.proceed();
        }
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(user.getUserRole());
        if (UserRoleEnum.BAN.equals(userRoleEnum)){
            // 账户被封禁 报错
            throw new BusinessExceptionXzh(ErrorCodeXzh.NO_AUTH_ERROR);
        }
        if (Objects.isNull(userRoleEnum)){
            // 用户没有登录
            throw new BusinessExceptionXzh(ErrorCodeXzh.NOT_LOGIN_ERROR);
        }

        // 必须管理员权限
        if (UserRoleEnum.ADMIN.equals(mustRoleEmun)){
            // 用户没有管理员权限 拒绝
            if (!UserRoleEnum.ADMIN.equals(userRoleEnum)){
                throw new BusinessExceptionXzh(ErrorCodeXzh.NO_AUTH_ERROR);
            }
        }
        // 通过放行
        return joinPoint.proceed();
    }
}
